package com.tydic.assistant.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by maliang on 2017/5/10.
 */
public class FileUtil {
    private static  final Logger logger = LoggerFactory.getLogger(FileUtil.class);


    /**
     * 将Classpath下的文件复制到指定目录
     * @param fileName
     * @param destPath
     */
    public static void copyFileFromClsPath(String fileName, String destPath) {
        InputStream srcIn = null;
        FileOutputStream fOut = null;
        try {
            srcIn = FileUtil.class.getClassLoader().getResourceAsStream(fileName);
            File file = new File(destPath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                fOut = new FileOutputStream(file);
                byte[] temp = new byte[1024];
                int len;
                while((len=srcIn.read(temp))!=-1){
                    fOut.write(temp,0,len);
                }
                fOut.flush();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                srcIn.close();
                fOut.close();
            } catch (Exception e) {
               logger.error(e.getMessage());
            }
        }
    }

    /**
     * 新增文件
     *
     * @param content      写入的内容
     * @param destFilePath 目标位置
     * @param isAppend     是否追加
     */
    public static void writeFile(ArrayList<String> content, String destFilePath, boolean isAppend) {
        FileWriter fw = null;
        BufferedWriter buf = null;
        try {
            File file = new File(destFilePath);
            File fileParent = file.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file, isAppend);
            buf = new BufferedWriter(fw);
            for (String str : content) {
                buf.write(str);
                buf.newLine();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                buf.close();
                fw.close();
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }
}
